<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item label="">
              <el-input v-model="searchForm.siteName" size="mini" placeholder="请输入检测场地" clearable></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-select v-model="searchForm.garageType" size="mini" placeholder="请选择库类型" clearable>
                <el-option :key="1" label="待检库" :value="1"></el-option>
                <el-option :key="2" label="完成库" :value="2"></el-option>
                <el-option :key="3" label="问题车型库" :value="3"></el-option>
                <el-option :key="4" label="待检无任务库" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button  size="mini" type="primary" @click="search">查询</el-button>
            </el-form-item>
            <!-- <el-form-item>
              <el-button  size="mini" type="primary" @click="clear">清空</el-button>
            </el-form-item> -->
          </el-form>
          <el-form :inline="true" size="medium">
            <el-form-item>
              <el-button type="primary"size="mini" @click="showAddDialogForm">新增</el-button>
            </el-form-item>
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button type="primary" size="mini" @click="search">刷新</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini"  @click="exportExcel">Excel导出</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="name"
        label="产品名称"
        min-width="120">
      </el-table-column>

      <el-table-column
        prop="model"
        label="产品型号"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="vin"
        label="VIN"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="carEnterpriseName"
        label="车企"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="prDate"
        label="生产年月"
        min-width="120">
        <template scope="scope">
          {{fmtDate(scope.row.prDate, "yyyy年MM月")}}
        </template>
      </el-table-column>
      <el-table-column
        prop="color"
        label="颜色"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="siteName"
        label="检测场地"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="garageType"
        label="库类型"
        min-width="120">
        <template scope="scope">
          <span v-if="scope.row.garageType==1">待检库</span>
          <span v-else-if="scope.row.garageType==2">完成库</span>
          <span v-else-if="scope.row.garageType==3">问题车型库</span>
          <span v-else-if="scope.row.garageType==4">待检无任务库</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="currentStatus"
        label="当前状态"
        min-width="120">
        <template scope="scope">
          <span v-if="scope.row.currentStatus==1">未入库</span>
          <span v-else-if="scope.row.currentStatus==2">已入库</span>
          <span v-else-if="scope.row.currentStatus==3">已出库</span>
          <span v-else-if="scope.row.currentStatus==4">已提车</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="carStatus"
        label="车辆状态"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="test"
        label="实验状态"
        min-width="120">
        <template scope="scope">
          <span v-if="scope.row.test==1">未实验</span>
          <span v-else-if="scope.row.test==2">实验中</span>
          <span v-else-if="scope.row.test==3">实验完成</span>
          <span v-else-if="scope.row.test==4">实验回退</span>

        </template>
      </el-table-column>
      <el-table-column
        prop="accomplishTime"
        label="实验完成时间"
        min-width="120">
        <template scope="scope">
          {{fmtDate(scope.row.accomplishTime)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="productTypeId1"
        label="申报类型"
        min-width="120">
        <template scope="scope">
          {{productTypeId(scope.row.productTypeId1,scope.row.productTypeId2)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="msg"
        label="回退原因"
        min-width="150">
      </el-table-column>
      <el-table-column
        prop="note"
        label="备注"
        min-width="150">
      </el-table-column>
      <el-table-column
        prop="address"
        label="操作"
        min-width="230">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="primary" @click="handleGarage(scope.$index, scope.row)">出入库</el-button>
          <!-- <el-button size="mini" type="primary" @click="workload(scope.$index, scope.row)">工作量</el-button> -->
          <el-button style="margin-top:8px" size="mini" type="primary" @click="handleTaskDone(scope.$index, scope.row)">实验任务跟踪</el-button>
          <el-button style="margin-top:8px" size="mini" type="primary" @click="TestCarLogs(scope.$index, scope.row)">查看历史</el-button>
          <el-button style="margin-top:8px" size="mini" type="primary" @click="handleCost(scope.$index, scope.row)">现场费用</el-button>
          <el-button style="margin-top:8px" size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog :title="getDoneTitle()" :visible.sync="doneFormVisible" width="700px" :close-on-click-modal="false">

        <el-row>
          <el-col :span="24">
            <table class="test-item-table">
              <tr>
                <th>申报类型</th>
                <th>项目代号</th>
                <th>检测项目</th>
                <th>数量</th>
                <th>检测机构</th>
                <th>
                  是否完成
                  <el-button type="primary" size="mini" plain @click.native.prevent="itemSelectAll">全选</el-button>
                </th>
              </tr>

              <tr v-for="(item,index) in taskItems">
                <td>{{item.name +'/'+item.name1}}</td>
                <td>{{item.serialNumber}}</td>
                <td>{{item.itemName}}</td>
                <td>{{item.num}}</td>
                <td>{{item.orgName}}</td>
                <td>
                  <input v-model="doneForm.doneTaskItemIds" type="checkbox" :value="item.id" />
                </td>
              </tr>

            </table>
          </el-col>
        </el-row>

      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button @click="doneFormVisible = false">取 消</el-button>
        <template v-if="taskItems!=null&&taskItems!=''">
        <el-button type="primary" @click.native.prevent="submitDoneSave">保存</el-button>
        <el-button type="primary" @click.native.prevent="submitDoneNext">提交</el-button>
        </template>
      </div>
    </el-dialog>

    <el-dialog title="查看历史" :visible.sync="carLogsVisible" width="700px" :close-on-click-modal="false">

        <el-row>
          <el-col :span="24">
            <table class="test-item-table">
              <tr>
                <th>任务完成时间</th>
                <th>任务回退时间</th>
                <th>任务回退原因</th>


              </tr>

              <tr v-for="(item,index) in carLogs">
                <td>{{fmtDate(item.accomplishTime)}}</td>
                <td>{{fmtDate(item.backTime)}}</td>
                <td>{{item.msg}}</td>
              </tr>

            </table>
          </el-col>
        </el-row>

      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button @click="carLogsVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="editForm.id==0?'新增':'修改'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item label="产品名称" label-width="100px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品型号" label-width="100px" prop="model">
          <el-input v-model="editForm.model" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="VIN" label-width="100px" prop="vin">
          <el-input v-model="editForm.vin" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="车企" label-width="100px" prop="carEnterpriseId">
          <el-select v-model="editForm.carEnterpriseId"  filterable  placeholder="请选择">
            <el-option
              v-for="item in carEntList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产年月" label-width="100px" prop="prDate">
          <el-date-picker
            v-model="editForm.prDate"
            type="month"
            value-format="timestamp"
            format="yyyy年MM月"
            placeholder="选择生产年月">
          </el-date-picker>
          <!-- <el-input v-model="editForm.prDate" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item label="颜色" label-width="100px" prop="color">
          <el-input v-model="editForm.color" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="editForm.note" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.id==0?'添 加':'修 改' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getTestCarList, addTestCar, updateTestCar, deleteTestCar} from "../../../api/test_car.js";
import {getAllTestCarEnterpriseList} from "../../../api/test_car_enterprise.js"
import {getTaskItemsCarAndLogs, done,getTestCarLogs} from '../../../api/test_car.js'
import {getToken} from '../../../common/utils/auth.js'
import axios from "axios";

export default {
  name: "testCarManage",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      doneFormVisible:false,
      carLogsVisible:false,
      taskItems:[],
      carLogs:[],
      doneTaskItems:[],
      doneForm:{
        doneTaskItemIds:[],
        next: 0,
        carId:'',
      },

      editForm: {
        id: 0,
        name: '',
        model: '',
        vin: '',
        carEnterpriseId: '',
        prDate: '',
        color: '',
        note: '',
      },
      searchForm: {
        siteName:'',
      },
      editRules: {
        name: [{ required: true, message:"请输入产品名称", trigger: 'blur'}],
        model: [{ required: true, message:"请输入产品型号", trigger: 'blur'}],
        vin: [{ required: true, message:"请输入VIN", trigger: 'blur'}],
        carEnterpriseId: [{ required: true, message:"请选择车企", trigger: 'blur'}],
        prDate: [{ required: true, message:"请选择生产年月", trigger: 'blur'}],
        color: [{ required: true, message:"请输入颜色", trigger: 'blur'}],
      },
      loadingDiv: null,

      carEntList:[],
    }
  },
  watch:{

  },
  mounted() {
    this.getDataList(this.currentPage);
    this.init();

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }
  },
  methods: {
    itemSelectAll(){
      let arr = [];

      for(let i in this.taskItems){
        arr.push(this.taskItems[i].id)
      }

      this.doneForm.doneTaskItemIds = arr;
    },

    fmtDate(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      return  util.fmtDate(new Date(d2), fmt);
    },

    productTypeId(productTypeId1,productTypeId2){
      if(productTypeId1==null||productTypeId1==''||productTypeId2==null||productTypeId2==''){
        return "";
      }
      let arr= productTypeId1.split(",");
      let arrTemps = productTypeId2.split(",");
      let newArr = []
      for (let i = 0, l = arr.length; i < l; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
          newArr.push(arr[i])
        }
      }
      var productTypeName = '';
      for(var i=0;i<newArr.length;i++){
        if(newArr[i]==1){
          productTypeName = productTypeName + " 公告.   "

        }
        if(newArr[i]==2){
          productTypeName = productTypeName + " 达标车型.   "
        }
        if(newArr[i]==3){
          productTypeName = productTypeName + " CCC.   "
        }
        if(newArr[i]==4){
          productTypeName = productTypeName + " 环保.   "
        }
        if(newArr[i]==19){
          productTypeName = productTypeName + " 其他.   "
        }
      }

      return productTypeName;
    },
    handleGarage(index, row){
      let item = {
        componentName:"testGarageManage",
        icon:"",
        path:"/test_car/test_garage_manage/"+row.id,
        title: row.name+"-出入库",
      };

      this.$store.commit("openTab",{item:item, router: (path)=>{this.$router.replace(path)}})

    },

    submitDoneSave(){
      this.doneForm.next = 0;
      this.submitDone();
    },
    submitDoneNext(){
      if(this.doneForm.doneTaskItemIds.length != this.taskItems.length){
        this.$message.error("请确认完成全部检测项目");
        return;
      }
      this.doneForm.next = 1;
      this.submitDone();
    },

    submitDone(){

      let title = "保存中"
      if(this.doneForm.next == 1){
          title = "完成中"
      }

      const loadingDiv = util.showLoading(title)
      done(this.doneForm).then(res => {
        if(res.code == 0) {
          this.$alert(res.msg, "失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(()=> {
              this.doneFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },

    handleCost(index, row){
      let item = {
        componentName:"testGarageCostManage",
        icon:"",
        path:"/test_car/test_garage_cost_manage/"+row.id,
        title: row.name+"-现场费用",
      };

      this.$store.commit("openTab",{item:item, router: (path)=>{this.$router.replace(path)}})

    },
    workload(index, row){
      let item = {
        componentName:"testWorkload",
        icon:"",
        path:"/test_car/test_workload/"+row.id,
        title: row.name+"-工作量",
      };

      this.$store.commit("openTab",{item:item, router: (path)=>{this.$router.replace(path)}})

    },

    exportExcel(){
      const loadingDiv = util.showLoading("正在导出EXCEL")

      let param = {};
      // param['siteId'] = this.$route.params.id;
      // param['siteId'] = this.$route.params.id;
      // param['siteId'] = this.$route.params.id;
      // param['siteId'] = this.$route.params.id;
      // param['siteId'] = this.$route.params.id;
      // param['siteId'] = this.$route.params.id;
      // console.log(param);

      let t = getToken();
      let headers = {"x-token": t};
      axios({
        method: 'post',
        url: this.$adminApiUrl + "/test-car/excel-export", // 请求地址
        data: param, // 参数
        headers: headers,
        responseType: 'blob' ,// 表明返回服务器返回的数据类型

      }).then(res=>{
        loadingDiv.close();
        let blob = new Blob([res.data], { type: 'application/xlsx' })
        let url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.href = url;
        let timeStr = "";//this.fmtDate(new Date(),"yyyyMMdd_hhmmss");
        link.download = '车辆管理'+ '.xlsx' // 重命名文件
        link.click()
        URL.revokeObjectURL(url)

      }).catch(err=>{
        // console.log(err);
        loadingDiv.close();
        this.$alert("导出失败,请检查网络", {dangerouslyUseHTMLString:true,type:'warning'})
      });
    },


    getDoneTitle(){
      return "关联任务";
      },


    init(){
      getAllTestCarEnterpriseList().then(res => {
        if(res.code == 1) {
          this.carEntList = res.data;
        }
      }).catch(res => {

      })
    },

    showAddDialogForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = '';
      }

      this.editForm.id = 0;
      this.editFormVisible = true;
    },
    handleEdit(index, row) {

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = row[key];
      }

      this.editFormVisible = true;

    },
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {
          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.id){
            loadingText = "修改中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = updateTestCar
          if(this.editForm.id == 0){
            func = addTestCar
          }
          func(this.editForm).then(res => {
            let title = "修改"
            if(this.editForm.id == 0){
              title = "添加"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.name+"?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteTestCar({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },

    TestCarLogs(index, row){
      getTestCarLogs({carId:row.id}).then(res=>{
        // console.log(res)
        if(res.code == 1){

          this.carLogs = res.data;


          this.carLogsVisible=true;
        }else{
          this.$message.error("加载信息失败")
        }
      });
    },

    handleTaskDone(index, row){

      getTaskItemsCarAndLogs({carId:row.id}).then(res=>{
        // console.log(res)
        if(res.code == 1){
          this.taskItems = res.data.taskItems;
          this.doneTaskItems = res.data.doneTaskItems;

          let arr = [];
          if(!util.isEmpty(this.doneTaskItems)){
            for(let i in this.doneTaskItems){
              arr.push(this.doneTaskItems[i].orderTaskItemCarId)
            }
          }
          this.doneForm.carId = row.id;
          this.doneForm.doneTaskItemIds = arr;
          this.doneRow = row;

          this.doneFormVisible=true;
        }else{
          this.$message.error("加载信息失败")
        }
      });
    },
    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getTestCarList({
        pageSize: this.pageSize,
        pageNum: pageNum,
        siteName : this.searchForm.siteName,
        garageType : this.searchForm.garageType,

      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },
    search() {
      this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
  // .test-item-table{
  //   width: 80%;
  //   border-collapse: collapse;

  //   th, td {
  //     width: 33.3%;
  //     text-align: center;
  //     border: 1px solid #CCC;
  //   }
  // }

  .test-item-table{
    width: 100%;
    border-collapse: collapse;
    tr{
      height: 40px;
    }

    th, td {
      width: 4%;
      text-align: center;
      border: 1px solid #CCC;
    }
    th {
      background-color: #EDF2FC;
    }
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
